package cn.iocoder.yudao.module.scrm.controller.admin.receivable;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.number.NumberUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.scrm.annotations.FieldCompareValidator;
import cn.iocoder.yudao.module.scrm.annotations.FieldCompareValidators;
import cn.iocoder.yudao.module.scrm.annotations.FieldRepeatValidator;
import cn.iocoder.yudao.module.scrm.annotations.FieldRepeatValidators;
import cn.iocoder.yudao.module.scrm.controller.admin.receivable.vo.ReceivablePageReqVO;
import cn.iocoder.yudao.module.scrm.controller.admin.receivable.vo.ReceivableRespVO;
import cn.iocoder.yudao.module.scrm.controller.admin.receivable.vo.ReceivableSaveReqVO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.customer.CustomerDO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.receivable.ReceivableDO;
import cn.iocoder.yudao.module.scrm.enums.common.CrmBizTypeEnum;
import cn.iocoder.yudao.module.scrm.enums.util.FieldNameType;
import cn.iocoder.yudao.module.scrm.feign.flow.ApproveApi;
import cn.iocoder.yudao.module.scrm.feign.flow.InstanceStartVO;
import cn.iocoder.yudao.module.scrm.feign.flow.R;
import cn.iocoder.yudao.module.scrm.service.customer.CustomerService;
import cn.iocoder.yudao.module.scrm.service.order.OrderService;
import cn.iocoder.yudao.module.scrm.service.receivable.ReceivableService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertListByFlatMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.common.util.collection.MapUtils.findAndThen;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "管理后台 - 回款")
@RestController
@RequestMapping("/scrm/receivable")
@Validated
public class ReceivableController {

    @Resource
    private ReceivableService receivableService;

    @Resource
    private CustomerService customerService;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private OrderService orderService;

    @Resource
    private DeptApi deptApi;

    @Resource
    private ApproveApi approve;

    @Resource
    private PermissionApi permissionApi;

    @PostMapping("/create")
    @Operation(summary = "创建回款")
    @PreAuthorize("@ss.hasPermission('scrm:receivable:create')")
    @FieldCompareValidators( foreignKeyType = CrmBizTypeEnum.CRM_RECEIVABLE,foreignKeyFieldName = FieldNameType.SCRM_PRICE,fieldCompareValidator = {
            @FieldCompareValidator(majorJeyType = CrmBizTypeEnum.CRM_ORDER,majorJeyFieldName = FieldNameType.SCRM_ORDER_TOTAL_MONEY,message = "金额限制！")
    })
    public CommonResult<Long> createReceivable(@Valid @RequestBody ReceivableSaveReqVO createReqVO) {
        return success(receivableService.createReceivable(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新回款")
    @PreAuthorize("@ss.hasPermission('scrm:receivable:update')")
    @FieldCompareValidators( foreignKeyType = CrmBizTypeEnum.CRM_RECEIVABLE,foreignKeyFieldName = FieldNameType.SCRM_PRICE,fieldCompareValidator = {
            @FieldCompareValidator(majorJeyType = CrmBizTypeEnum.CRM_ORDER,majorJeyFieldName = FieldNameType.SCRM_ORDER_TOTAL_MONEY,message = "金额限制！")
    })
    public CommonResult<Boolean> updateReceivable(@Valid @RequestBody ReceivableSaveReqVO updateReqVO) {
        receivableService.updateReceivable(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除回款")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('scrm:receivable:delete')")
    public CommonResult<Boolean> deleteReceivable(@RequestParam("id") Long id) {
        receivableService.deleteReceivable(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得回款")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('scrm:receivable:query')")
    public CommonResult<ReceivableRespVO> getReceivable(@RequestParam("id") Long id) {
        ReceivableDO receivable = receivableService.getReceivable(id);
        return success(buildReceivableDetail(receivable));
    }


    @GetMapping("/page")
    @Operation(summary = "获得回款分页")
    @PreAuthorize("@ss.hasPermission('scrm:receivable:query')")
    public CommonResult<PageResult<ReceivableRespVO>> getReceivablePage(@Valid ReceivablePageReqVO pageReqVO) {
        //不是超级管理员默认查询自己的数据-是超级管理员直接查询所有的
        Long loginUserId = getLoginUserId();
        if(CollectionUtils.isAnyEmpty(pageReqVO.getOwnerUserId()) && !permissionApi.roleIsSuperAdmin(loginUserId).getCheckedData()) {
            pageReqVO.setOwnerUserId(Collections.singletonList(Objects.requireNonNull(getLoginUserId()).toString()));
        }
        PageResult<ReceivableDO> pageResult = receivableService.getReceivablePage(pageReqVO);
        return success(new PageResult<>(buildReceivableDetailList(pageResult.getList()), pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出回款 Excel")
    @PreAuthorize("@ss.hasPermission('scrm:receivable:export')")
    @OperateLog(type = EXPORT)
    public void exportReceivableExcel(@Valid ReceivablePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ReceivableDO> list = receivableService.getReceivablePage(pageReqVO).getList();
        List<ReceivableRespVO> receivableRespVOList = buildReceivableDetailList(list);

        // 导出 Excel
        ExcelUtils.writeAuto(response, "回款.xls", "数据", ReceivableRespVO.class,
                receivableRespVOList,ReceivableRespVO.class);
    }

    @PostMapping("/approve")
    @Operation(summary = "回款审批")
    public R approve(@Valid @RequestBody InstanceStartVO vo) {
        return approve.instanceStart(vo);
    }

    private ReceivableRespVO buildReceivableDetail(ReceivableDO receivable) {
        if (receivable == null) {
            return null;
        }
        return buildReceivableDetailList(Collections.singletonList(receivable)).get(0);
    }

    private List<ReceivableRespVO> buildReceivableDetailList(List<ReceivableDO> receivableList) {
        if (CollUtil.isEmpty(receivableList)) {
            return Collections.emptyList();
        }
        // 1.1 获取客户列表
        Map<Long, CustomerDO> customerMap = customerService.getCustomerMap(
                convertSet(receivableList, ReceivableDO::getCustomerId));
        // 1.2 获取创建人、负责人列表
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMapNotCheckDataPermission(convertListByFlatMap(receivableList,
                contact -> Stream.of(NumberUtils.parseLong(contact.getCreator()), convertToLong(contact.getOwnerUserId()))));

        Map<Long, DeptRespDTO> deptMap = deptApi.getDeptMapNotCheckDataPermission(convertSet(userMap.values(), AdminUserRespDTO::getDeptId));

        Map<Integer, OrderDO> orderMap = orderService.getOrderMap(convertSet(receivableList, ReceivableDO::getOrderId));
        // 2. 拼接结果
        return BeanUtils.toBean(receivableList, ReceivableRespVO.class, receivableVO -> {
            // 2.1 拼接客户名称
            findAndThen(customerMap, receivableVO.getCustomerId(), customer -> receivableVO.setCustomerName(customer.getName()));
            // 2.2 拼接负责人、部门
            findAndThen(userMap, receivableVO.getOwnerUserId(), user -> {
                receivableVO.setOwnerUserName(user.getNickname());
                findAndThen(deptMap, user.getDeptId(), dept -> receivableVO.setOwnerUserDeptName(dept.getName()));
            });
            // 2.4 拼接负责人姓名
            findAndThen(userMap, receivableVO.getCreator(), user -> {
                receivableVO.setCreatorName(user.getNickname());
            });
            // 2.5 拼接订单号
            MapUtils.findAndThen(orderMap, receivableVO.getOrderId(), order -> receivableVO.setOrderTitle(order.getTitle()));
        });
    }


    // 辅助方法：将 String 转换为 Long
    private Long convertToLong(String id) {
        try {
            return id != null ? Long.valueOf(id) : null;
        } catch (NumberFormatException e) {
            // 处理转换异常，返回 null 或者记录日志
            return null;
        }
    }
}